/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef REALMD_UI_UI_SUBSYSTEM_H_
#define REALMD_UI_UI_SUBSYSTEM_H_

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <boost/unordered_map.hpp>
#include "node/util/log.h"
#include "node/net/tcp/tcp_server.h"
#include "node/db/rdb/details/mysql_database.h"
#include "node/app/subsystem.h"
#include "node/sys/event.h"
#include "node/sys/mutex.h"
#include "ui_realmlist.h"
#include "ui_socket.h"

#define __NODE_RDB  ::node::rdb::MySQLDatabase

class UISubSystem : public ::node::app::SubSystem
{
public:
    struct Statics {
        int total_connections;
        int authed_connections;
    };

    UISubSystem(const char *name);
    virtual ~UISubSystem(void);

    virtual bool Initialize(void);
    virtual void Run(void);
    virtual void Uninitialize(void);
    virtual void OnSignal(int signal);

    UISocket* GetUserSocket(int id);
    void AddUserSocket(int id, UISocket *sock);

    Statics GetStatics(void);

private:
    void UpdateUserSockets(void);

    ::node::util::Log log_;
    ::node::tcp::TcpServer net_;
    __NODE_RDB db_;
    int db_ping_time_;

    UIRealmList realms_;
    int realms_update_time_;

    volatile bool running_;
    ::node::sys::Event stop_event_;

    ::boost::unordered_map<int, UISocket*> user_sockets_;
    ::boost::unordered_map<int, UISocket*> old_user_sockets_;
    ::node::sys::Mutex user_sockets_lock_;
};

#endif // REALMD_UI_UI_SUBSYSTEM_H_
